package com.atguigu.spzx.manager.service.impl;

import com.atguigu.spzx.manager.properties.MyMinioProperties;
import com.atguigu.spzx.manager.service.FileUploadService;
import io.minio.*;
import io.minio.errors.MinioException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * @author MikeCoder
 * @create 2023-12-0521:17
 * @description:
 * @verson:
 */
@Service
@Transactional
public class FileUploadServiceImpl implements FileUploadService {
    @Autowired
    private MyMinioProperties myMinioProperties;
    @Override
    public String fileUpload(MultipartFile file) {
        try {
            //创建一个Minio的客户端对象
            MinioClient minioClient =
                    MinioClient.builder()
                            //设置服务器地址
                            .endpoint(myMinioProperties.getEndpointUrl())
                            .credentials(myMinioProperties.getAccessKey(), myMinioProperties.getSecretKey())
                            .build();

            // 查找指定bucket是否存在
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(myMinioProperties.getBucketName()).build());
            if (!found) {
                // 没有找到，就创建一个
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(myMinioProperties.getBucketName()).build());
            } else {
                System.out.println("Bucket "+myMinioProperties.getBucketName()+" already exists.");
            }
            //创建文件流对象
            InputStream stream = file.getInputStream();

            PutObjectArgs build = PutObjectArgs.builder()
                    //指定要上传到哪一个bucket
                    .bucket(myMinioProperties.getBucketName())
                    //上传的流
                    .stream(stream, file.getSize(), -1)
                    //上传到服务器之后的名字
                    .object(file.getOriginalFilename())
                    .build();
            // 上传文件到minio服务器上
            minioClient.putObject(build);
            //设置返回的文件地址
            String fileUrl = myMinioProperties.getEndpointUrl()+"/"+myMinioProperties.getBucketName()+"/"+file.getOriginalFilename();
            return fileUrl;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
